package net.retorx

import javax.ws.rs._
import com.google.inject.{Singleton, Inject}
import org.jboss.resteasy.annotations.cache.{NoCache, Cache}

@Singleton
@Path("/imageContent")
class ImageContentService @Inject() (imageContentDAO:ImageContentDAO) {

    @NoCache
	@GET
	@Path("/latest")
	@Produces(Array("text/json"))
	def getLatestImages = {
		imageContentDAO.getLatestImages
	}

    @NoCache
	@GET
	@Path("/tags")
	@Produces(Array("text/json"))
	def getTags = {
		imageContentDAO.getTags
	}

    @NoCache
	@GET
	@Path("/tag/{tag}")
	@Produces(Array("text/json"))
	def getImagesForTag(@PathParam("tag") tag : String) = {
		imageContentDAO.getImageContentByTag(tag)
	}

    @NoCache
	@GET
	@Path("/all")
	@Produces(Array("text/json"))
	def getAllImageContent = {
		imageContentDAO.getAllImageContent
	}

    @Cache(maxAge = 3600)
	@GET
	@Path("/{id}")
	@Produces(Array("text/json"))
	def getImageContent(@PathParam("id") id: String) = {
		imageContentDAO.getImageContent(id)
	}

    @Cache(maxAge = 3600)
	@GET
	@Path("/thumb/{id}/{name}")
	@Produces(Array{"image/png"})
	def getAltThumbnailFile(@PathParam("id") id: String, @PathParam("name") name: String ) = {
		val imageFile = getAltImageFileObject(id, name)
		imageFile.getThumb
	}


	private def getAltImageFileObject(id: String, name: String) = {
		val imageContent = getImageContent(id)
		imageContent.getAltImageFile(name)
	}

    @Cache(maxAge = 3600)
	@GET
	@Path("/image/{id}/{name}")
	@Produces(Array{"image/png"})
	def getAltImageFile(@PathParam("id")id: String, @PathParam("name") name: String) = {
		getAltImageFileObject(id, name).getFile
	}

    @Cache(maxAge = 3600, isPrivate = false)
	@GET
	@Path("/image/{id}")
	@Produces(Array{"image/png"})
	def getImageFile(@PathParam("id") id: String) = {
		//pause()
		val imageContent = getImageContent(id)
		imageContent.getImageFile.getFile
	}

    @Cache(maxAge = 3600, isPrivate = false)
	@GET
	@Path("/thumb/{id}")
	@Produces(Array{"image/png"})
	def getThumbnailFile(@PathParam("id") id: String) = {
		val imageContent = getImageContent(id)
		imageContent.getImageFile.getThumb
	}

    @Cache(maxAge = 3600)
	@GET
	@Path("/thumb/grayscale/{id}")
	@Produces(Array{"image/png"})
	def getGrayscaleThumbnailFile(@PathParam("id") id: String) = {
		val imageContent = getImageContent(id)
		imageContent.getImageFile.getGrayscaleThumb
	}

	private def pause() {
		try {
			Thread.sleep(10000)
		} catch {
			case e: Exception => e.printStackTrace()
		}
	}
}
